var express = require('express');
var router = express.Router();
var querystring = require('querystring');
var util = require('util');
var path = require('path');
var log4js = require('../utils/logger');
var config = require('../../config');
var ui_pub_sub = require('../../db/Ui_pub_sub_collection_If');

var Logger = log4js.getLogger(path.basename(__filename));
Logger.setLevel(config.LogLevel);

var DEFAULT_LIMIT = 1;
var MAX_LIMIT = 25;


router.get('/*', function(req, res, next) {
  Logger.debug('req.session.id:' + req.session.id);
  Logger.info('[line:' + __line + ']' + ' req.url:' + req.url);
  var topic = req.query.topic;
  var limit = req.query.limit == undefined ? req.query.limit : Number(req.query.limit);
  var begintime = req.query.begintime == undefined ? req.query.begintime : Number(req.query.begintime);
  var endtime = req.query.endtime == undefined ? req.query.endtime : Number(req.query.endtime);

  Logger.debug('req.query.topic:' + topic);
  Logger.debug('req.query.limit:' + limit);
  Logger.debug('req.query.begintime:' + begintime);
  Logger.debug('req.query.endtime:' + endtime);

  if(topic == undefined) {
    Logger.error('[line:' + __line + ']' + ' unexpected case_1: topic == undefined');
  } else if(begintime != undefined && endtime != undefined && begintime > endtime) {
    Logger.error('[line:' + __line + ']' + ' unexpected case_2: begintime:' + begintime + ' > endtime:' + endtime);
  } else {

    if(begintime != undefined || endtime != undefined) {
      if(begintime == undefined) {
        begintime = 0;
      }

      if(endtime == undefined) {
        endtime = new Date().getTime();
      }

      if(limit == undefined) {
        limit = MAX_LIMIT;
      } else if(limit > MAX_LIMIT){
        limit = MAX_LIMIT;
      }
      getDataBetweenTime(res, topic, begintime, endtime, limit);

    } else {
      if(limit == undefined) {
        limit = DEFAULT_LIMIT;
      }
      getLastOne(res, topic, limit);
    }
  } 
});

function getLastOne(res, topic, limit) {
  ui_pub_sub.QueryDataLimit(topic, limit).then(function(datas) {
    Logger.info('[line:' + __line + ']' + ' datas:' + datas);
    var json = {errCode: 0, errMsg: '', datas: datas};
    res.json(json);
  }).catch(function(err, msg) {
    Logger.error('[line:' + __line + ']' + ' err:' + err + ',msg:' + msg);
    var json = {errCode: 1000, errMsg: 'db failed'};
    res.json(json);
  });
}

function getDataBetweenTime(res, topic, begintime, endtime, limit) {
  ui_pub_sub.QueryDataBetweenTimeLimit(topic, begintime, endtime, limit).then(function(datas) {
    Logger.info(datas);
    var json = {errCode: 0, errMsg: '', datas: datas};
    res.json(json);
  }).catch(function(err, msg) {
    Logger.error('[line:' + __line + ']' + ' err:' + err + ',msg:' + msg);
    var json = {errCode: 1000, errMsg: 'db failed'};
    res.json(json);
  });
}

module.exports = router;